package com.lge.clock.worldclock;

import java.io.IOException;
import java.util.*;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.SearchView.OnCloseListener;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

import com.lge.clock.AlarmClockActivity;
import com.lge.clock.R;
import com.lge.clock.WorldClockFragment;
import com.lge.clock.sui.JapaneseLocaleUtil;
import com.lge.clock.util.CommonUtil;
import com.lge.clock.util.CommonUtil.OPERATOR;
import com.lge.clock.worldclock.cities.CityDBManager;
import com.lge.clock.worldclock.cities.CityInformation;
import com.lge.clock.worldclock.util.HangulUtils;
import com.lge.clock.worldclock.util.IndexedListUtil;
import com.lge.clock.worldclock.util.WCPreferences;
import com.lge.sui.widget.list2.SUIIndexedListView;
import com.lge.sui.widget.list2.adapter.SUIAlphabetIndexable;
import com.lge.sui.widget.list2.adapter.SUIArrayAlphabetSectionIndexer;
import com.lge.sui.widget.list2.adapter.SUIArrayIndexedListAdapter;
import com.lge.sui.widget.list2.adapter.SUIIndexedListAdapter;
import com.lge.sui.widget.list2.adapter.SUISectionIndexer;
import com.lge.sui.widget.list2.locale.SUILocaleUtil;

/**
 * @author lge.com
 */
public class ListSearchActivity extends Activity implements TextWatcher, SearchView.OnQueryTextListener {
    /**
     * Field focusedViewCache.
     */
    public static View focusedViewCache = null;
    private static final String TAG = "ListSearchActivity";
    private SearchView searchEdit;
    private TextView searchEmpty;
    private ListView matchList;
    private SUIIndexedListView listView;
 //   private HashMap<Integer, String> pos_map = null;
    private ListSearchAdapter mCityListAdapter;
    private CityDBManager mCityManager;
    
    private String localeInfo;

	private ActionBar actionBar;
	
	//TD#29416 fixed by mo2sangbong.lee@lge.com 2011.07.22 Start    
//	private long mBeforClickedTime = 0;
//	private long mAfterClickedTime = 0;
	private boolean isLowOnSpace = false;//[hyunjung78.park][1406] 2011.10.12 
	//TD#29416 fixed by mo2sangbong.lee@lge.com 2011.07.22 End	
	
	//[suhaeng.lee][6749] 2012.4.27
	//Define Object JapaneseLocaleUtil. We need it only one. so, create static Object
	private static SUILocaleUtil japaneseLocaleUtil = new JapaneseLocaleUtil();
	
    /**
     * Field adapter.
     */
    IndexedListAdapter adapter;
    
	/**
	 * Field cityListItems.
	 */
	ArrayList<CityInformation> cityListItems;
	/**
	 * Field data.
	 */
	List<Data> data = new ArrayList<Data>();
	/**
	 * Field searchListItems.
	 */
	ArrayList<CityInformation> searchListItems = new ArrayList<CityInformation>();
	/**
	 * Field firstSearchResult.
	 */
	ArrayList<CityInformation> firstSearchResult = new ArrayList<CityInformation>();
	/**
	 * Field secondSearchResult.
	 */
	ArrayList<CityInformation> secondSearchResult  = new ArrayList<CityInformation>();
	
	private boolean mIsInit = false;
	
	private Handler mHandler = new Handler() {
	public void handleMessage(Message msg) {
			InputMethodManager iMethodManager;
			iMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			
			if(iMethodManager != null){
				iMethodManager.showSoftInput(searchEdit, InputMethodManager.SHOW_IMPLICIT);
			}
			
			mIsInit = true;
			super.handleMessage(msg);
		}
	};

	/**
	 * Method onCreate.
	 */
	@Override 
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
		//[hyunjung78.park][1406] 2011.10.12 START
        isLowOnSpace = CommonUtil.isLowOnSpaceMemory(this);
		if(isLowOnSpace) {

			requestWindowFeature(Window.FEATURE_NO_TITLE);
			getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE |
	                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
			AlertDialog.Builder builder = new AlertDialog.Builder(this);			
			builder.setIconAttribute(android.R.attr.alertDialogIcon);
			builder.setTitle(com.lge.clock.R.string.sp_low_internal_storage_title_NORMAL);
			builder.setMessage(com.lge.clock.R.string.sp_low_memory_NORMAL);
			builder.setPositiveButton(android.R.string.yes,
        		new DialogInterface.OnClickListener() {
        			public void onClick(DialogInterface dialog, int which) {
        				Log.d(TAG, "===onCreate yes  " );
						finish();
						
        			}
        		});
			builder.setOnKeyListener(new OnKeyListener() {
				public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
						switch (keyCode) 
						{
							case KeyEvent.KEYCODE_BACK:
								finish();
								return true;
							default :
								return false;
						}
				}
			});
			builder.show();
			return;
		}
		//[hyunjung78.park][1406] 2011.10.12 END
        
        mIsInit = false;
        actionBar = getActionBar();
//	    actionBar.setDisplayShowTitleEnabled(false);
	    actionBar.setTitle(R.string.sp_NEWCITY_NORMAL);
	    actionBar.setIcon(R.drawable.world_clock);
	    actionBar.setDisplayShowHomeEnabled(true);

		// set list mode on search
        WCPreferences wcPref = new WCPreferences(this);
        wcPref.setSearchType(true);
        
        setContentView(R.layout.worldclock_indexed_city_list);
        
        searchEmpty = (TextView)findViewById(R.id.emptyText);
        matchList = (ListView)findViewById(R.id.searchList);
        
		searchEdit = (SearchView)(findViewById(R.id.searchEdit));
		
		searchEdit.onActionViewExpanded();
		
		searchEdit.setOnCloseListener(new OnCloseListener(){
			@Override
			public boolean onClose() {
				// don't iconify me!!
				return true;
			}});
		
		searchEdit.setOnQueryTextListener(this);
		searchEdit.setIconified(false);
		searchEdit.requestFocus();
        searchEmpty.setVisibility(View.GONE);
        matchList.setVisibility(View.GONE);
        
       
        try {
			mCityManager = CityDBManager.getInstance(this);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
        cityListItems = mCityManager.getCityInfoAllList();
        searchListItems.addAll(cityListItems);
        
        for(int i = 0 ; i < cityListItems.size() ; i++)
        {
        	data.add(new Data(cityListItems.get(i)));
        }
        
        listView = (SUIIndexedListView)findViewById(android.R.id.list);
        

        //adapter = new IndexedListAdapter(this, R.layout.worldclock_indexed_city_list_item, data, new SUIArrayAlphabetSectionIndexer<Data>(this, data));
        
        //[suhaeng.lee][6749] 2012.4.27 START
        //We have different Indexer options for Language setting.
        //ko,ar,bg,mk,ru,zh,fa,th,kk,uk,el => (1) use short indexer because they need not Alphabet Indexer.
        //ja => (1) use short indexer, (2) use japanese "他" instead of "?", so use japaneseLocaleUtil.
        
        boolean useShortIndex;
        String language = CityInformation.getLanguageMode().substring(0, 2);
          
        if(language.equals("ko")||language.equals("ar")||language.equals("bg")||language.equals("mk")||language.equals("ru")||language.equals("zh")
        		||language.equals("fa")||language.equals("th")||language.equals("kk")||language.equals("uk")||language.equals("el")){    
        	useShortIndex = true;
        }else{
        	useShortIndex = false;
        }            
        
        if(language.equals("ja")){
        	adapter = new IndexedListAdapter(this, R.layout.worldclock_indexed_city_list_item, data, new SUIArrayAlphabetSectionIndexer<Data>(this, data, japaneseLocaleUtil));
        }else{
        	adapter = new IndexedListAdapter(this, R.layout.worldclock_indexed_city_list_item, data, new SUIArrayAlphabetSectionIndexer<Data>(this, data, useShortIndex));
        }
        //[suhaeng.lee][6749] 2012.4.27 END
        
        listView.setAdapter((SUIIndexedListAdapter)adapter);
        
        mCityListAdapter = new ListSearchAdapter(this, R.layout.worldclock_matched_list_item, searchListItems);
        
        matchList.setAdapter(mCityListAdapter);
        
        matchList.setVerticalScrollBarEnabled(true);
        
        listView.setOnTouchListener(new OnTouchListener() 
		{
			public boolean onTouch(View arg0, MotionEvent arg1) 
			{
				if(!mIsInit)
					return true;
				hideSoftKeyboard();
				listView.requestFocus();
				return false;
			}
		});
        
        matchList.setOnTouchListener(new OnTouchListener() 
		{
			public boolean onTouch(View arg0, MotionEvent arg1) 
			{
				hideSoftKeyboard();
				matchList.requestFocus();
				return false;
			}
		});
        
        listView.setOnChildClickListener(new OnChildClickListener() {
			
			public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
					int childPosition, long id) {
				if(!mIsInit)
					return true;
				Intent intent = new Intent(getBaseContext(), ListSearchActivity.class);
                Data selectCity = (Data) adapter.getChild(groupPosition, childPosition);
                
                //moon.dongchul@lge.com WBT #297447 2012-01-05
                if(selectCity == null)return false;
                if(!isVerifyCheck(selectCity.mCity)) {
                	
                	if(CommonUtil.isSprintOperator()){
                		Toast.makeText(getApplicationContext(), String.format(getString(R.string.sp_msg_dup_city_list_NORMAL), selectCity.mCity.getCityName()), Toast.LENGTH_SHORT).show();
                	}else{
                		Toast.makeText(getApplicationContext(), R.string.msg_dup_city_list, Toast.LENGTH_SHORT).show();	
                	}
                    return false;
                }
                
                selectCity.mCity.setRegistValue(CityDBManager.CITY_SET_SETTED);
                String strRowId = "";
                strRowId = mCityManager.addCityNum(selectCity.mCity.getID());
                int cityId = Integer.parseInt(strRowId.trim());
                intent.putExtra("city_id", cityId);
                setResult(RESULT_OK, intent);
                finish();
                return false;
			}
		});
        
		
        matchList.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int index,
					long arg3) {
			    Intent intent = new Intent(getBaseContext(), WorldClockFragment.class);
			    CityInformation selectCity = mCityListAdapter.getItem(index);
			    
			    if(!isVerifyCheck(selectCity)) {
			    	
			    	if(CommonUtil.isSprintOperator()){
			    		Toast.makeText(getApplicationContext(), String.format(getString(R.string.sp_msg_dup_city_list_NORMAL), selectCity.getCityName()), Toast.LENGTH_SHORT).show();
			    	}else{
			    		Toast.makeText(getApplicationContext(), R.string.msg_dup_city_list, Toast.LENGTH_SHORT).show();
			    	}

			        return;
			    }
			    
			    selectCity.setRegistValue(CityDBManager.CITY_SET_SETTED);
			    String strRowId = "";
                strRowId = mCityManager.addCityNum(selectCity.getID());                  
                int cityId = Integer.parseInt(strRowId.trim());
                intent.putExtra("city_id", cityId);
                setResult(RESULT_OK, intent);
			    finish();
			}
        	
		});
        
        if(searchListItems.size() > 0){
            StringBuilder builder = new StringBuilder(16);
            List<String> list = null;
 //           pos_map = IndexedListUtil.getPosMap();
            
            list = IndexedListUtil.getTokenList();
            
            for (int i = 0; i < list.size(); i++)
            {
                builder.append(list.get(i));
            }
        }
        
		mHandler.sendMessageDelayed(mHandler.obtainMessage(), 500);
		
//		if(focusedViewCache != null){
//			searchList.requestChildFocus(focusedViewCache, searchList);
//		}
//		searchList.expandAllGroup();
	}
	
	/**
	 * Method onPause.
	 */
	@Override
	protected void onPause() {
		super.onPause();
		hideSoftKeyboard();
	}
	
	
	
	@Override
	protected void onResume() {
		super.onResume();
		Log.d(TAG, "===onResume ");
		//[hyunjung78.park][1406] 2011.10.12 START
		isLowOnSpace = CommonUtil.isLowOnSpaceMemory(this);
		if(isLowOnSpace){ 
			isLowOnSpace = false;
			return;  
		}
		mIsInit = false;
		//[hyunjung78.park][1406] 2011.10.12 END
		searchEdit.requestFocus();
		mHandler.sendMessageDelayed(mHandler.obtainMessage(), 500);
		
 		// [suhyun99.kim][1428] 2011.10.13. START
		if(listView != null) {
		    listView.removeOverlayPopup(); 
		    listView.expandAllGroup();//[suhaeng.lee][6594] 2012.04.23
			//listView.refresh(); //[suhaeng.lee][3218] 2012.01.16
		}
		// [suhyun99.kim][1428] 2011.10.13. END
	}

	/**
	 * Method onDestroy.
	 */
	@Override
	protected void onDestroy() {
		super.onDestroy();
		//hideSoftKeyboard();
	}
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.worldclock_list_menu,menu);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()){
		case R.id.searchMap :
			item.setEnabled(false);
    		finish();
    		Intent  intent = new Intent(this, MapSearchActivity.class);
    		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            
            hideSoftKeyboard();
            break;
			
		}
		return super.onOptionsItemSelected(item);
	}

	private void hideSoftKeyboard() 
	{
		//TD#16801 cosmo merged by mo2sangbong.lee@lge.com 2011.07.23 Start
		InputMethodManager inputMethodManager = (InputMethodManager)
			getSystemService(Context.INPUT_METHOD_SERVICE);
		// WBT TD#151868 Fixed Start
		if (inputMethodManager != null && matchList != null) {//[hyunjung78.park][1406] 2011.10.12 
			inputMethodManager.hideSoftInputFromWindow(matchList.getWindowToken(), 0);
		}
		// WBT TD#151868 Fixed End
		//TD#16801 cosmo merged by mo2sangbong.lee@lge.com 2011.07.23 End

    }

    private boolean isVerifyCheck(CityInformation selectCity) {
	    ArrayList<CityInformation> tempCityArray;
	    tempCityArray = mCityManager.getWorldClockList(this);
	    
	    for(CityInformation item : tempCityArray) {
	        if(item.getID() == selectCity.getID()) return false;
	    }
	    
        return true;
    }
    
	/**
	 * Method onClick.
	 * @see android.view.View$OnClickListener#onClick(View) */
//	public void onClick(View v) {
//		switch(v.getId()){
//    	case R.id.searchButton:
//    		
//    		/*[START] 2011.10.06 suein1209.kim @blocking the 3D map enter and leave button cuz out of memory*/
//    		/*if mode is MAP_ENTER_FLAG = false, wait!*/
//    		if(!CommonUtil.MAP_ENTER_FLAG){
//    			return;
//    		} //end Of if 
//    		/*[END] 2011.10.06 suein1209.kim @blocking the 3D map enter and leave button cuz out of memory*/    		
//    		
//    		//TD#29416 fixed by mo2sangbong.lee@lge.com 2011.07.22 Start
//    		long mTimeGap = 0;
//    		
//    		mAfterClickedTime = SystemClock.elapsedRealtime();
//    		mTimeGap = mAfterClickedTime - mBeforClickedTime;
//    		if (mTimeGap < ViewConfiguration.getDoubleTapTimeout() * 3) {
//    			return;
//    		} else {
//    			mBeforClickedTime = SystemClock.elapsedRealtime();
//    		}
//    		//TD#29416 fixed by mo2sangbong.lee@lge.com 2011.07.22 End    		
//    		finish();
//    		Intent  intent = new Intent(this, MapSearchActivity.class); 
//            startActivity(intent);
//            
//            hideSoftKeyboard();
//            
//            /*[START] 2011.10.06 suein1209.kim @blocking the 3D map enter and leave button cuz out of memory*/
//            /*check 3d map leave delay time*/
//	        CommonUtil.LEAVE_EXECUTOR.execute(new ThMeditate(CommonUtil.MAP_DELAY_ENTER_TIME, EmGubunMedit.MAP_LEAVE));
//	        /*[END] 2011.10.06 suein1209.kim @blocking the 3D map enter and leave button cuz out of memory*/
//            
//    		break;
//    		default :
//		}
//	}

	/**
	 * Method afterTextChanged.
	 * @see android.text.TextWatcher#afterTextChanged(Editable) */
	public void afterTextChanged(Editable s) {
	}

	/**
	 * Method beforeTextChanged.
	 * @see android.text.TextWatcher#beforeTextChanged(CharSequence, int, int, int) */
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
	}

	/**
	 * Method onTextChanged.
	 * @see android.text.TextWatcher#onTextChanged(CharSequence, int, int, int) */
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		String searchString = s.toString();
		mCityListAdapter.clear();
		mCityListAdapter.setMarkString(searchString);
		
		if(searchString.length() == 0) {
		    searchListItems.clear();
		    searchListItems.addAll(cityListItems);
		    set_Visibility();
		    return;
		}
		
		{

			if(CityInformation.LANGUAGE_MODE_KOREAN.equals(CityInformation.getLanguageMode()) || "ko_KR".equals(CityInformation.getLanguageMode()))
			{
				searchCityContainChosung(searchString);
			}
			else
			{
				searchCity(searchString);
			}
		}
	}
	
    private void searchCity(String search) {
        searchListItems.clear();
        firstSearchResult.clear();
        secondSearchResult.clear();
        
        try {
        	firstSearchResult = mCityManager.getSearchCityList(search, CityDBManager.SEARCH_FIRST_GROUP);
        	secondSearchResult = mCityManager.getSearchCityList(search, CityDBManager.SEARCH_SECOND_GROUP);

		    if(firstSearchResult != null) //WBT_nullpointer
		    mCityListAdapter.setIndexPosition(firstSearchResult.size());

		    if(firstSearchResult != null) //WBT_nullpointer
        	searchListItems.addAll(firstSearchResult);

		    if(secondSearchResult != null) //WBT_nullpointer
        	searchListItems.addAll(secondSearchResult);
        } catch (Exception e) {
        	e.printStackTrace();
        }
		
		set_Visibility();
	}
	
    private void searchCityContainChosung(String inputString) {
        searchListItems.clear();
        firstSearchResult.clear();
        secondSearchResult.clear();

        try {
        	firstSearchResult = mCityManager.getSearchCityList(inputString, CityDBManager.SEARCH_FIRST_GROUP);
        	secondSearchResult = mCityManager.getSearchCityList(inputString, CityDBManager.SEARCH_SECOND_GROUP);

        	// WBT nullpointer
        	if(firstSearchResult != null) {
        		mCityListAdapter.setIndexPosition(firstSearchResult.size());
        		searchListItems.addAll(firstSearchResult);
        	}
        	
        	if(secondSearchResult != null)
        		searchListItems.addAll(secondSearchResult);
        } catch (Exception e) {
        	e.printStackTrace();
        }
        
		set_Visibility();
	}
    
    private void set_Visibility() {
    	if(searchEdit.getQuery().length() == 0){
    		searchEmpty.setVisibility(View.GONE);
            matchList.setVisibility(View.GONE);
            
            listView.setVisibility(View.VISIBLE);
            adapter.notifyDataSetChanged();
            listView.setFocusable(true);
    	}
    	else if((searchEdit.getQuery().length() > 0) && (searchListItems.size() == 0))  {
            searchEmpty.setVisibility(View.VISIBLE);
            listView.setVisibility(View.GONE);
            matchList.setVisibility(View.GONE);
        }
        else
        {
            searchEmpty.setVisibility(View.GONE);
            listView.setVisibility(View.GONE);
            
            matchList.setVisibility(View.VISIBLE);
            mCityListAdapter.notifyDataSetChanged();
            matchList.setFocusable(true);
        }
    }
	
	/**
	 * Method onKeyDown.
	 * @author lge.com
	 * @see android.view.KeyEvent$Callback#onKeyDown(int, KeyEvent) */
	@Override 
	public boolean onKeyDown(int keyCode, KeyEvent event){
    	
		if(keyCode == KeyEvent.KEYCODE_BACK){
			finish();
			setResult(RESULT_OK, new Intent(this, WorldClockFragment.class));
			return true;
		}
		return false;
	}
	
	
	/**
	 * @author lge.com
	 */
	public class Data implements SUIAlphabetIndexable
	{
		String mCityName;
		String mCountryName;
		String mGMT;
		CityInformation mCity;
		
		/**
		 * Constructor for Data.
		 */
		public Data(CityInformation city)
		{
			mCityName = city.getCityName();
			mCountryName = city.getCountryName();
			mGMT = city.getGmtString();
			mCity = city;
		}
		
		public String getTargetWord() 
		{
			return mCityName;
		}
	}
	
	/**
	 * @author lge.com
	 */
	public static class IndexedListAdapter extends SUIArrayIndexedListAdapter<Data>
	{
		/**
		 * Constructor for IndexedListAdapter.
		 */
		public IndexedListAdapter(Context context, int childLayout,	List<Data> data, SUISectionIndexer indexer) 
		{
			super(context, childLayout, data, indexer);
		}

		/**
		 * Method bindChildView.
		 */
		@Override
		public void bindChildView(View view, Data data) 
		{	
			String city_info_string = data.mCityName;
			String country_info_string = data.mCountryName;
	        

	        
	        if (view != null) 
	        {

	        	TextView city = (TextView)view.findViewById(R.id.city_item_textview);
	        	TextView country = (TextView)view.findViewById(R.id.country_item_textview);

	        	if(!"".equals(city_info_string.trim()) || city_info_string != null)// || !"".equals(city_gmt_string.trim()) || city_gmt_string != null)
	        	{
	        		//WBT fix td 207891, 207892
		        	if (city != null)
		        	{
		        		city.setText(city_info_string);
		        		country.setText(country_info_string);
		        		//city.setText(Html.fromHtml(city_info_string));//+"("+city_gmt_string+")"));
		        		//country.setText(Html.fromHtml(country_info_string));
		        		//city.setSelected(true); // seungchul.kang@lge.com worldclock_citilist_item.xml marquee fixed
		        	}
	        	}
			 }
		}

		/**
		 * Method refreshIndexer.
		 */
		@Override
		public void refreshIndexer(List<Data> data) 
		{
			//SUISectionIndexer indexer = new SUIArrayAlphabetIndexer<Data>( getContext(), data);
			//[suhaeng.lee][6749] 2012.4.27 START
			boolean useShortIndex;
	        String language = CityInformation.getLanguageMode().substring(0, 2);
	        
	        if(language.equals("ko")){
	        	useShortIndex = true;
	        }else{
	        	useShortIndex = false;
	        } 

			SUISectionIndexer indexer;
			if(language.equals("ja")){
				indexer = new SUIArrayAlphabetSectionIndexer<Data>( getContext(), data, japaneseLocaleUtil);
			}else{
				indexer = new SUIArrayAlphabetSectionIndexer<Data>( getContext(), data, useShortIndex);
			}
		    //[suhaeng.lee][6749] 2012.4.27 END
			
			 setIndexer(indexer);
		}

		/**
		 * Method getPositionForSection.
		 * @see android.widget.SectionIndexer#getPositionForSection(int) */
		@Override
		public int getPositionForSection(int sectionIndex) 
		{
			try
			{
				return super.getPositionForSection(sectionIndex);
			}
			catch(IndexOutOfBoundsException e)
			{
				if(AlarmClockActivity.LOG)Log.e(TAG,"IndexOutOfBoundsException");
			}
			return -1;
		}

		/**
		 * Method getDataCount.
		 * @see com.lge.sui.widget.list2.SUISectionIndexer#getDataCount(int) */
		@Override
		public int getDataCount(int sectionIndex) 
		{
			try
			{
				return super.getDataCount(sectionIndex);
			}
			catch(IndexOutOfBoundsException e)
			{
				if(AlarmClockActivity.LOG)Log.e(TAG,"IndexOutOfBoundsException");
			}
			return -1;
		}		
	}
	
	
	/**
	 * @author lge.com
	 */
	public class ListSearchAdapter extends ArrayAdapter<CityInformation> {
	    private String _mark;
	    private int index_position;
	    
	    private LayoutInflater inflater;
        //private Iterator<Integer> pos_map_iter;
	    
	    
	    /**
	     * Constructor for ListSearchAdapter.
	     */
	    public ListSearchAdapter(Context context, int textViewResourceId,
	            List<CityInformation> list) {
	        super(context, textViewResourceId, list);
	        _mark = "";
	        if (!initialization(context, list)) return;
	    }
	    
        private boolean initialization(Context context, List<CityInformation> list)
        {
            if (list == null || list.isEmpty()) return false;
            
            inflater = LayoutInflater.from(context);
            return true;
        }
	    
	    public void setMarkString(String mark) {
	        _mark = mark;
	    }
	    
	    public void setIndexPosition(int pos) {
	        index_position = pos;
	    }
	    
	    /**
	     * Method getView.
	     * @see android.widget.Adapter#getView(int, View, ViewGroup) */
	    public View getView(int position, View convertView, ViewGroup parent) {
	        CityInformation item = getItem(position);
	        String city_info_string = item.getCityName();
	        String country_info_string = item.getCountryName();
	        
	        if(convertView == null) {
	            convertView = inflater.inflate(R.layout.worldclock_matched_list_item, null);
	        }
	        
	        TextView index = (TextView)convertView.findViewById(R.id.indexbar);
	        //index.setVisibility(View.GONE);
	        TextView city = (TextView)convertView.findViewById(R.id.city_item_textview);
	        TextView country = (TextView)convertView.findViewById(R.id.country_item_textview);
	        
	        set_index(index, position);
	        
	    	if(position == index_position) 
	    	{
//	    		convertView.findViewById(R.id.indexbar_line_head).setVisibility(View.VISIBLE);
//	    		convertView.findViewById(R.id.indexbar_line).setVisibility(View.VISIBLE);
	    		convertView.findViewById(R.id.list_item_layout).setVisibility(View.VISIBLE);
	    		convertView.findViewById(R.id.list_space).setVisibility(View.GONE);
	    	}
	    	else if(position == 0)
	    	{
//	    		convertView.findViewById(R.id.indexbar_line_head).setVisibility(View.GONE);
//	    		convertView.findViewById(R.id.indexbar_line).setVisibility(View.VISIBLE);
	    		convertView.findViewById(R.id.list_item_layout).setVisibility(View.VISIBLE);
	    		convertView.findViewById(R.id.list_space).setVisibility(View.GONE);
	    	}
	    	else
	    	{
//	    		convertView.findViewById(R.id.indexbar_line_head).setVisibility(View.GONE);
//	    		convertView.findViewById(R.id.indexbar_line).setVisibility(View.VISIBLE);
	    		convertView.findViewById(R.id.list_item_layout).setVisibility(View.GONE);
	    		convertView.findViewById(R.id.list_space).setVisibility(View.VISIBLE);
	    	}
	    	
	        try
	        {
	        	if(city_info_string != null) {
	        		/*[START] 2012.03.28 suein1209.kim INTERNAL_TEST.WBT_12 - Defect #329171*/
	        		String cityNameStr = markString(city_info_string);
	        		if(cityNameStr != null){
	        			city.setText(Html.fromHtml(cityNameStr));//+"("+city_gmt_string+")"));
	        		}else{
	        			city.setText("Error");
	        		} //End Of if
	        		/*[END] 2012.03.28 suein1209.kim INTERNAL_TEST.WBT_12 - Defect #329171*/
	        	}
	        	
	        	if(country_info_string != null){
	        		country.setText(Html.fromHtml(markString(country_info_string)));
	        	}
	        }
	        catch(NullPointerException e)
	        {
	        	e.printStackTrace();
	        }
	        
	        return convertView;
	    }
	    

	    private void set_index(TextView index, int position) 
	    {
	    	if(position == index_position) 
	    	{
	    		index.setText(R.string.group_Title_AZ);
	    		index.setVisibility(View.VISIBLE);
	    	}
	    	else if(position == 0)
	    	{
	    		if(CityInformation.LANGUAGE_MODE_KOREAN.equals(CityInformation.getLanguageMode()) || "ko_KR".equals(CityInformation.getLanguageMode())){
	    			index.setText(hangulToChoseoung(_mark.substring(0, 1)));
	    		}else{
	    			index.setText(_mark.substring(0, 1));
	    		}
	    		index.setVisibility(View.VISIBLE);
	    	} else {
	    		index.setVisibility(View.GONE);
	    	}
	    }
	    
	    private String hangulToChoseoung(String s){
	    	String result = "";
	    	for(int i = 0 ; i < s.length() ; i++){
	    		char comVal = s.charAt(i);
	    		if(comVal >= 0xAC00){
	    			result = HangulUtils.getHangulInitialSound(s);
	    		}else{
	    			result = s;
	    		}
	    	}
	    	return result;
	    }

        private String markString(String data) {
	        String resultFormat = null;
	        
		    if(CityInformation.isHangul(_mark)){
		    	resultFormat = markKoreanString(data);
		    }else{
		    	resultFormat = markEnglishString(data);
		    }
	        return resultFormat;
	    }

        private String markEnglishString(String data) {
            int searchIdx = 0;
            String temp[] = null;
            String resultFormat = null;
			String format = null;
            

            format = getContext().getResources().getString(R.string.style_resource_color);
            
            if(_mark.equals("")) {
                searchIdx = -1;
            }
            else {
                searchIdx = data.toLowerCase().indexOf(_mark.toLowerCase());
                temp = data.toLowerCase().split(_mark.toLowerCase());
                if((searchIdx > 0) && (temp.length==0)){
                	temp = data.toLowerCase().split("\\"+_mark.toLowerCase()); 
            	}
            }
            if(searchIdx < 0) {
                resultFormat = data;
            }
            else {
                int j = 0;
                String tempstring = null;
                String markstring = null;
                for(int i=0; i<temp.length; i++){
                    tempstring = data.substring(j, j+temp[i].length());
                    j += temp[i].length();
                    if(j+_mark.length() <= data.length()) {
                        markstring = data.substring(j, j + _mark.length());
                    }
                    
                    if(resultFormat==null){
                    	if(markstring != null){
                    		resultFormat = (tempstring+String.format(format, TextUtils.htmlEncode(markstring)));
                        }
                    }else{
                        if(i+1 == temp.length){
                            if(data.substring(data.length()-markstring.length(), data.length()).equals(markstring)){
                                resultFormat =  resultFormat + (tempstring+String.format(format, TextUtils.htmlEncode(markstring)));                                    
                            }else{
                                resultFormat =  resultFormat + tempstring;
                            }
                        }else{
                            resultFormat =  resultFormat + (tempstring + String.format(format, TextUtils.htmlEncode(markstring)));
                        }
                    }
                    j += _mark.length();
                }
                if(data.equalsIgnoreCase(_mark) && resultFormat == null) {
                    resultFormat = String.format(format, TextUtils.htmlEncode(data));
                }
            }
            
            return resultFormat;
        }

        private String markKoreanString(String data) {
            String markString = null;
            String replaceString = null;
            String resultFormat = null;
            String format = null;
            
            format = getContext().getResources().getString(R.string.style_resource_color);
            
            resultFormat = data;
            
            for(int j = 0; j < (data.length() - _mark.length() + 1); j++)
            {
                markString = HangulUtils.getHangulInitialSound(j , data, _mark);
                
                int index = 0;
                
                if(markString != null){
                	index = markString.indexOf(_mark);
                }
                
                if(index != -1)
                {
                    replaceString = data.substring(index + j, index + j +_mark.length());
                    resultFormat = resultFormat.replaceAll(replaceString, 
                            String.format(format, TextUtils.htmlEncode(replaceString)));
                    break;
                }
            }
            
            return resultFormat;
        }
	}   
	@Override
	public boolean onQueryTextChange(String searchString) {
		mCityListAdapter.clear();
		mCityListAdapter.setMarkString(searchString);
		//[suhaeng.lee][6330] 2012.04.11 add trim() to skip searching if searchView dont have words but have only spaces.
		if(searchString.trim().length() == 0) {
		    searchListItems.clear();
		    searchListItems.addAll(cityListItems);
		    set_Visibility();
		    return true;
		}
		
		{
			if(CityInformation.LANGUAGE_MODE_KOREAN.equals(CityInformation.getLanguageMode()) || "ko_KR".equals(CityInformation.getLanguageMode()))
			{
				searchCityContainChosung(searchString);
			}
			else
			{
				searchCity(searchString);
			}
		}
		return true;
	}

	@Override
	public boolean onQueryTextSubmit(String query) {
		// TODO Auto-generated method stub
		hideSoftKeyboard();
		searchEdit.clearFocus();
		return false;
	}
	//[suhaeng.lee][2969] 2012.01.09 START
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
//		InputMethodManager iMethodManager;
//		iMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		
		switch (keyCode) { 		
		case KeyEvent.KEYCODE_MENU :
			//[haesun.jung][WBT#310905] 2012.01.24
//			if(iMethodManager != null && !iMethodManager.isActive()){
//				searchEdit.requestFocus();
//			}
			return true;
		case KeyEvent.KEYCODE_BACK :
			
			return true; 
		
		default :
			break;
		}
	
	return false; 	
	}
	//[suhaeng.lee][2969] 2012.01.09 END
	
	//[suhaeng.lee][6594] 2012.04.23 SUIIndexedListView issue when locale changed START
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		outState.putString("locale", localeInfo);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onRestoreInstanceState(savedInstanceState);
		String savedLocale = savedInstanceState.getString("locale", null);
		if(Locale.getDefault().toString() != savedLocale){
			listView.refresh();
		}
	}
	//[suhaeng.lee][6594] 2012.04.23 SUIIndexedListView issue when locale changed END
	
	
}
